const fs = require('fs')
const path = require('path')
const mongoose = require('mongoose')
const ObjectId = mongoose.Types.ObjectId
const { host } = require('../../../../config')
const { Swiper } = require('../../schema')

mongoose.connect('mongodb://127.0.0.1:27017/sportswear').then()

const swiperCollection = mongoose.model('swiper', Swiper)

// 插入轮播图数据
function insertBannerList (doc) {
    let _doc = {
        bannerid: ObjectId(),
        alt: '图片信息',
        link: '图片跳转链接',
        img: '图片的网络资源路径'
    }
    _doc = Object.assign(_doc, doc)
    const record = new swiperCollection(_doc)
    return new Promise((resolve, reject) => {
        record.save().then(() => resolve(_doc)).catch(err => reject(err))
    })
}

// 获取轮播图数据
function readBannerList () {
    return new Promise((resolve, reject) => {
        swiperCollection.find({}).then(res => {
            resolve(res)
        }, err => {
            reject(err)
        })
    })
}

// 删除一个轮播图
function removeBannerList (bannerid) {
    return new Promise((resolve, reject) => {
        swiperCollection.find({ bannerid: ObjectId(bannerid) }).then(res => {
            if (!res.length) {
                reject('要删除的轮播图不存在')
                return
            }
            const { img } = res[0]
            let absolutePath = path.join(__dirname, '../../../../', img.replace(host + '/static', 'server'))
            // 执行数据库的删除
            swiperCollection.deleteOne({ bannerid: ObjectId(bannerid) }).then(res => {
                try {
                    // 执行文件的删除
                    fs.rmSync(absolutePath)
                    resolve('删除成功')
                } catch (e) {
                    if(e.toString().includes('is not a function')){
                        resolve('数据删除成功，但是服务器硬盘图片资源无法删除！兼容性问题，请提升node版本至16.13.2')
                    }else{
                        resolve('数据删除成功,网络图片资源无法在服务器硬盘删除（正常）')
                    }
                }
            }, err => {
                resolve('删除失败，未知原因')
            })
        })
    })
}

function removeBannerListAll () {
    return new Promise((resolve, reject) => {
        swiperCollection.find({}).then(res=>{
            res.forEach(item=>{
                let absolutePath = path.join(__dirname, '../../../../', item.img.replace(host + '/static', 'server'))
                try {
                    // 执行文件的删除
                    fs.rmSync(absolutePath)
                } catch (e) {
                    // 什么也不写
                    if(e.toString().includes('is not a function')){
                        resolve('数据全部删除成功，但是服务器硬盘图片资源无法删除！兼容性问题，请提升node版本至16.13.2')
                    }else{
                        resolve('数据全部删除成功,部分网络图片资源无法在服务器硬盘删除（正常）')
                    }
                }
            })
            swiperCollection.deleteMany({}).then(res => {
                resolve('删除成功')
            }, err => {
                reject('删除失败，请稍后重试')
            })
        })
    })
}

module.exports = {
    insertBannerList,
    readBannerList,
    removeBannerList,
    removeBannerListAll
}
